package com.moon.app;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.moon.R;
import com.moon.adapter.ReplyListAdapter;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.model.JsonResult;
import com.moon.model.Reply;
import com.moon.model.ReplyListJsonResult;
import com.moon.model.Topic;
import com.moon.model.TopicJsonResult;
import com.moon.utils.BitmapImageCache;
import com.moon.utils.DateUtils;
import com.moon.utils.HttpClientUtils;
import com.moon.utils.JacksonUtils;

/**
 * @author paul
 * @date 2014年5月18日
 */
public class TopicViewActivity extends AbstractActivity implements
        SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = TopicViewActivity.class.getSimpleName();

    ImageLoader                 imageLoader;

    //topic内容
    ImageView                   userImage;
    TextView                    userName;
    TextView                    topicTitle;
    TextView                    topicContent;
    ImageView                   topicImage1;
    String                      image1Url;
    ImageView                   topicImage2;
    String                      image2Url;
    ImageView                   topicImage3;
    String                      image3Url;
    TextView                    topicGmtCreate;

    //reply部分
    ImageView                   btnZan;                                       //赞
    ImageView                   btnReply;                                     //回复
    EditText                    replyContent;
    BootstrapButton             btnReplyCommit;
    LinearLayout                replyLinearLayout;

    PullToRefreshListView       listView;
    SwipeRefreshLayout          topicSwipeLayout;

    private LinkedList<Reply>   replyList;
    private ReplyListAdapter    adapter;

    Long                        bottomReplyId;
    Long                        topReplyId;
    Long                        topicId;

    RequestQueue  mQueue ;
    StopWatch watch = new StopWatch();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        watch.start();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.topic_view);
        
        mQueue = Volley.newRequestQueue(getApplicationContext());  
        
        Intent intent = getIntent();
        Topic topic = (Topic) intent.getSerializableExtra(MoonConstants.TOPIC_OBJECT_KEY);
        topicId = topic.getId();

        initView();
        watch.stop();
        Log.e(TAG, "init view "+String.valueOf(watch.getTime()));
        //watch.start();

        //取topic
        getTopic(topic.getId());
        //new GetTopicTask().execute(String.valueOf(topic.getId()));
        //取reply
        listReplyString(true);
    }

    private void topicInit(Topic topic) {
        loadImage(MoonConstants.MOON_DOMAIN_STATIC_HEAD + topic.getImgUrl(),userImage);
        //readBitmapViaVolley(mQueue,MoonConstants.MOON_DOMAIN_STATIC_HEAD + topic.getImgUrl(),userImage);
//        imageLoader.DisplayImage(MoonConstants.MOON_DOMAIN_STATIC_HEAD + topic.getImgUrl(),
//                userImage);
        userName.setText(topic.getUserName());
        topicTitle.setText(topic.getTitle());
        topicContent.setText(topic.getContent());
        topicGmtCreate.setText(DateUtils.formatDate2String(topic.getGmtCreate(),
                DateUtils.DATEPATTERN_TIME));
       
        if (StringUtils.isNotBlank(topic.getImages())) {
            String[] images = topic.getImages().split("\\|");
            for (int i = 0; i < images.length; i++) {
                if (i == 0) {
                    image1Url=images[0];
                    loadImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC_SMALL + images[0],topicImage1);
                    //readBitmapViaVolley(mQueue,MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[0],topicImage1);
//                    imageLoader.DisplayImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[0],
//                            topicImage1);
                    topicImage1.setVisibility(View.VISIBLE);
                }
                if (i == 1) {
                    image2Url=images[1];
                    loadImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC_SMALL + images[1],topicImage2);
                    //readBitmapViaVolley(mQueue,MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[1],topicImage2);

//                    imageLoader.DisplayImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[1],
//                            topicImage2);
                    topicImage2.setVisibility(View.VISIBLE);
                }
                if (i == 2) {
                    image3Url=images[2];
                    loadImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC_SMALL + images[2],topicImage3);
                    //readBitmapViaVolley(mQueue,MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[2],topicImage3);

//                    imageLoader.DisplayImage(MoonConstants.MOON_DOMAIN_STATIC_TOPIC + images[2],
//                            topicImage3);
                    topicImage3.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * @param topic
     */
    private void loadImage(String url,ImageView view) {
        ImageLoader imageLoader = new ImageLoader(mQueue, BitmapImageCache.getInstance());
        
        //defaultImageResId  图片加载完成前显示的默认图片  0时不显示
        //errorImageResId    图片加载出错时显示的错误图片  0时不显示
        ImageListener listener = ImageLoader.getImageListener(view,
                0, R.drawable.app_panel_pic_icon);
        imageLoader.get(url, listener);
    }

    
    
    //这是ImageRequest的写法  
//    public void readBitmapViaVolley(RequestQueue mQueue,String imgUrl, final ImageView imageView) {
//        ImageRequest imgRequest = new ImageRequest(imgUrl,
//                new Response.Listener<Bitmap>() {
//                    @Override
//                    public void onResponse(Bitmap arg0) {
//                        // TODO Auto-generated method stub
//                        imageView.setImageBitmap(arg0);
//                    }
//                }, 
//                50, 
//                50, 
//                Bitmap.Config.ARGB_8888, 
//                new ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError arg0) {
//                        
//                    }
//                });
//        mQueue.add(imgRequest);
//    }
//    
    private void initView() {
        //imageLoader = new ImageLoader(this);
        userImage = (ImageView) findViewById(R.id.user_image);
        userName = (TextView) findViewById(R.id.user_name);
        topicTitle = (TextView) findViewById(R.id.topic_title);
        topicContent = (TextView) findViewById(R.id.topic_content);
        topicImage1 = (ImageView) findViewById(R.id.view_topic_image_1);
        topicImage1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(TopicViewActivity.this, ShowImageActivity.class);
                intent.putExtra(MoonConstants.SHOW_IMAGE_URL, image1Url);
                startActivity(intent);
            }
        });
        topicImage2 = (ImageView) findViewById(R.id.view_topic_image_2);
        topicImage2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(TopicViewActivity.this, ShowImageActivity.class);
                intent.putExtra(MoonConstants.SHOW_IMAGE_URL, image2Url);
                startActivity(intent);
            }
        });
        topicImage3 = (ImageView) findViewById(R.id.view_topic_image_3);
        topicImage3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(TopicViewActivity.this, ShowImageActivity.class);
                intent.putExtra(MoonConstants.SHOW_IMAGE_URL, image3Url);
                startActivity(intent);
            }
        });
        topicGmtCreate = (TextView) findViewById(R.id.topic_gmt_create);
        btnZan = (ImageView) findViewById(R.id.btn_zan);
        //评论
        btnReply = (ImageView) findViewById(R.id.btn_reply);
        btnReply.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                replyLinearLayout.setVisibility(View.VISIBLE);
                replyContent.setFocusable(true);
            }
        });

        replyContent = (EditText) findViewById(R.id.view_reply_content);
        btnReplyCommit = (BootstrapButton) findViewById(R.id.btnReplyCommit);
        btnReplyCommit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(replyContent.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                new CreateReplyTask().execute(String.valueOf(topicId),
                        String.valueOf(getUser().getId()), replyContent.getText().toString(),String.valueOf(bottomReplyId));
            }
        });

        replyLinearLayout = (LinearLayout) findViewById(R.id.reply_layout);

        topicSwipeLayout = (SwipeRefreshLayout) this.findViewById(R.id.reply_swipe_list);
        topicSwipeLayout.setOnRefreshListener(this);

        // 顶部刷新的样式
        topicSwipeLayout.setColorScheme(android.R.color.holo_green_light,
                android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        listView = (PullToRefreshListView) this.findViewById(R.id.reply_list_view);
        listView.setMode(Mode.BOTH);//上下拉都可以
        listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置  --重新加载第一页数据
                //使用SwipeRefreshLayout.OnRefreshListener 来做了,没有在此处理,也可以使用这块
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项   -- 把数据加到已有的topicList

                listReplyString(false);

                //new FinishRefresh().execute();  

            }
        });
        replyList = new LinkedList<Reply>();//用于展现
        adapter = new ReplyListAdapter(this, replyList);
        listView.setAdapter(adapter);
    }

    
    //为什么用volley会慢.  表现主要是发起请求慢
    private void getTopic(Long topicId) {
//        String requestUrl = "/mobile_topic/topic_view.do?topicId=" + topicId + "&userId="
//                + getUser().getId();
        String requestUrl = "/mobile_topic/topic_view.do?topicId=" + topicId ;
        watch.reset();
        watch.start();

        //RequestQueue mQueue1 = Volley.newRequestQueue(getApplicationContext());
        mQueue.add(new StringRequest(MoonConstants.MOON_DOMAIN + requestUrl,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        watch.stop();
                        Log.e(TAG, "getTopic from network "+String.valueOf(watch.getTime()));
                        TopicJsonResult result = JacksonUtils.fromJSON(response,
                                TopicJsonResult.class);
                        if (result.isSuccess()) {
                            topicInit(result.getObject());
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "获取更新失败", Toast.LENGTH_SHORT)
                                .show();

                    }

                }));
        //mQueue.start();
    }

    private class GetTopicTask extends AsyncTask<String, String, Topic> {
        
        String requestUrl = "/mobile_topic/topic_view.do";

        @Override
        protected Topic doInBackground(String... params) {
            StopWatch watch1 = new StopWatch();
            watch1.start();
            try {
                //请求服务器
                List<NameValuePair> pairs = convertParams(params);
                String json = HttpClientUtils.post(MoonConstants.MOON_DOMAIN + requestUrl, pairs);
                watch1.stop();
                Log.e(TAG, "getTopic from network "+String.valueOf(watch.getTime()));

                TopicJsonResult result = JacksonUtils.fromJSON(json,
                        TopicJsonResult.class);
                if (result.isSuccess()) {
                    return result.getObject();
                }
                return null;
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            //Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }

        //要更新UI,必须重写此方法,不能在doInBackground直接操作UI
        @Override
        protected void onPostExecute(Topic topic) {
            if(topic != null){
                topicInit(topic);
            }
        }

        /**
         * 组装request参数
         * 
         * @param params
         * @return
         */
        private List<NameValuePair> convertParams(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("topicId", params[0]));
       

            return pairs;
        }

    }
    
    
    /*
     * (non-Javadoc)
     * @see
     * android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener#onRefresh
     * ()
     */
    @Override
    public void onRefresh() {
        topicSwipeLayout.setRefreshing(false);
        listReplyString(true);
    }

    //读取评论列表
    private void listReplyString(final boolean isPullDown) {
        //回复先不分页
        Integer pageNo = 1;
        Integer pageSize = 10;

        try {
            //拼装url
            String requestUrl = "/mobile_topic/list_reply.do?pageNo=" + pageNo + "&topicId="
                    + topicId + "&pageSize=" + pageSize;
            if (!isPullDown && bottomReplyId!= null) {//此时取bottomTopicId后面的20条
                requestUrl = requestUrl + "&bottomReplyId=" + bottomReplyId;
            }
            //RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
            mQueue.add(new StringRequest(MoonConstants.MOON_DOMAIN + requestUrl,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            ReplyListJsonResult result = JacksonUtils.fromJSON(response,
                                    ReplyListJsonResult.class);
                            if (result.isSuccess()) {
                                //插入数据List
                                addReplyList(isPullDown,result.getObject());

                                //更新ui
                                adapter.notifyDataSetChanged();

                                //完成刷新ui
                                listView.onRefreshComplete();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getApplicationContext(), "获取更新失败", Toast.LENGTH_SHORT)
                                    .show();

                        }

                    }));
            mQueue.start();
        } catch (Exception e) {
            Log.e(TAG, "listTopic error", e);
        }
    }

    private void addReplyList(boolean isPullDown, LinkedList<Reply> replys) {
        if (replys == null || replys.size() == 0) {
            return;
        }

        //下拉为重置数据
        //上拉为加载数据
        if (isPullDown) {
            replyList.clear();
        }
        for (Reply reply : replys) {
            replyList.addLast(reply);
        }

        //更新上下id   
        if (isPullDown) {
            //顶部ID
            topReplyId = replys.getFirst().getId();
            //底部ID
            bottomReplyId = replys.getLast().getId();
        } else {
            bottomReplyId = replys.getLast().getId();
            if (topReplyId == null) {
                topReplyId = replys.getFirst().getId();
            }
        }
        
   
    }

    private class CreateReplyTask extends AsyncTask<String, String, Boolean> {
        String requestUrl = "/mobile_topic/create_reply.do";

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                //请求服务器
                List<NameValuePair> pairs = convertParams(params);
                String json = HttpClientUtils.post(MoonConstants.MOON_DOMAIN + requestUrl, pairs);
                JsonResult result = JacksonUtils.fromJSON(json, JsonResult.class);
                if (result.isSuccess()) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            //Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }

        //要更新UI,必须重写此方法,不能在doInBackground直接操作UI
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                //返回列表
                listReplyString(true);
                replyLinearLayout.setVisibility(View.GONE);
            } else {
                Toast.makeText(getApplicationContext(), "获取评价失败", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * 组装request参数
         * 
         * @param params
         * @return
         */
        private List<NameValuePair> convertParams(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair(MoonConstants.REPLY_TOPIC_ID, params[0]));
            pairs.add(new BasicNameValuePair(MoonConstants.REPLY_USER_ID, params[1]));
            pairs.add(new BasicNameValuePair(MoonConstants.REPLY_CONTENT, params[2]));
            pairs.add(new BasicNameValuePair(MoonConstants.REPLY_BOTTOM_REPLY_ID, params[3]));

            return pairs;
        }

    }

    //以下是使用JsonObjectRequest   使用POST提交数据 后端无法接收到数据?
    //    private void createReply() {
    //        try {
    //            String requestUrl = "/mobile_topic/create_reply.do";
    //            final JSONObject jsonRequest = new JSONObject();
    //            jsonRequest.put(MoonConstants.REPLY_TOPIC_ID, topicId);
    //            jsonRequest.put(MoonConstants.REPLY_USER_ID, getUser().getId());
    //            jsonRequest.put(MoonConstants.REPLY_CONTENT, replyContent.getText().toString());
    //
    //            RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
    //            mQueue.add(new JsonObjectRequest(Method.POST, MoonConstants.MOON_DOMAIN + requestUrl,
    //                    jsonRequest, new Response.Listener<JSONObject>() {
    //                        @Override
    //                        public void onResponse(JSONObject response) {
    //                            try {
    //                                if (response.getBoolean("success")) {
    //                                    listReplyString();
    //                                }
    //                            } catch (JSONException e) {
    //                                Log.e(TAG, "listReplyString ERROR", e);
    //                            }
    //                        }
    //                    }, new Response.ErrorListener() {
    //                        @Override
    //                        public void onErrorResponse(VolleyError error) {
    //                            Toast.makeText(getApplicationContext(), "获取评价失败", Toast.LENGTH_SHORT)
    //                                    .show();
    //                        }
    //                    }));
    //            mQueue.start();
    //        } catch (Exception e) {
    //            Log.e(TAG, "createReply error", e);
    //        }
    //
    //    }

}
